<template>
	<view class="page">
		<!-- 商品信息卡片 -->
		<view class="goods-card">
			<view class="goods-image-box">
				<image :src="getimg(goodsDetail.image || goodsDetail.images)" class="goods-image" mode="aspectFill"></image>
			</view>
			<view class="goods-info">
				<text class="goods-title">{{ goodsDetail.title }}</text>
				<view class="price-box">
					<text class="price-symbol">¥</text>
					<text class="price-value">{{ goodsDetail.s_price }}</text>
					<text class="price-unit" v-if="goodsDetail.unit">/{{ goodsDetail.unit }}</text>
				</view>
			</view>
		</view>

		<!-- 购买数量 -->
		<view class="quantity-card">
			<view class="card-row">
				<text class="label">购买数量</text>
				<view class="quantity-control">
					<view class="quantity-btn" :class="{disabled: quantity <= 1}" @click="decreaseQuantity">
						<uni-icons type="minus" size="16" :color="quantity <= 1 ? '#cccccc' : '#666666'"></uni-icons>
					</view>
					<view class="quantity-input">
						<text class="quantity-value">{{ quantity }}</text>
					</view>
					<view class="quantity-btn" @click="increaseQuantity">
						<uni-icons type="plus" size="16" color="#666666"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 配送方式 -->
		<view class="delivery-card">
			<view class="card-title">
				<text class="title-text">配送方式</text>
			</view>
			<view class="delivery-options">
				<view class="delivery-option" :class="{active: deliveryType === 1}" @click="selectDelivery(1)">
					<view class="option-icon">
						<uni-icons type="cart-filled" size="24" :color="deliveryType === 1 ? '#667eea' : '#999999'"></uni-icons>
					</view>
					<view class="option-content">
						<text class="option-title" :class="{active: deliveryType === 1}">快递物流</text>
						<text class="option-desc">送货上门，安全便捷</text>
					</view>
					<view class="option-check">
						<uni-icons v-if="deliveryType === 1" type="checkmarkempty" size="20" color="#667eea"></uni-icons>
						<view v-else class="check-circle"></view>
					</view>
				</view>
				<view class="delivery-option" :class="{active: deliveryType === 0}" @click="selectDelivery(0)">
					<view class="option-icon">
						<uni-icons type="home-filled" size="24" :color="deliveryType === 0 ? '#667eea' : '#999999'"></uni-icons>
					</view>
					<view class="option-content">
						<text class="option-title" :class="{active: deliveryType === 0}">门店自提</text>
						<text class="option-desc">订单自动完成已收货</text>
					</view>
					<view class="option-check">
						<uni-icons v-if="deliveryType === 0" type="checkmarkempty" size="20" color="#667eea"></uni-icons>
						<view v-else class="check-circle"></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 收货地址 - 只在快递物流时显示 -->
		<view class="address-card" v-if="deliveryType === 1" @click="selectAddress">
			<view class="address-icon">
				<uni-icons type="location-filled" size="24" color="#667eea"></uni-icons>
			</view>
			<view class="address-content" v-if="address">
				<view class="address-header">
					<text class="address-name">{{ address.name }}</text>
					<text class="address-phone">{{ address.mobile }}</text>
				</view>
				<text class="address-detail">{{ address.province }} {{ address.city }} {{ address.area }} {{ address.address }}</text>
			</view>
			<view class="address-content" v-else>
				<text class="address-empty">请选择收货地址</text>
			</view>
			<view class="address-arrow">
				<uni-icons type="right" size="16" color="#999999"></uni-icons>
			</view>
		</view>

		<!-- 小计 -->
		<view class="total-card">
			<view class="card-row">
				<text class="label">小计</text>
				<view class="total-price">
					<text class="total-symbol">¥</text>
					<text class="total-value">{{ totalPrice }}</text>
				</view>
			</view>
		</view>

		<!-- 占位 -->
		<view style="height: 140rpx;"></view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="price-summary">
				<text class="summary-label">合计：</text>
				<text class="summary-symbol">¥</text>
				<text class="summary-value">{{ totalPrice }}</text>
			</view>
			<view class="btn-confirm" @click="confirmBuy">
				<text class="btn-text">立即支付</text>
			</view>
		</view>
		
		<!-- 支付弹窗 -->
		<combinepay 
			v-if="showpay" 
			:price="totalPrice" 
			v-on:onshowpay="showpay = false"
			v-on:gopay="gopay"
		></combinepay>
	</view>
</template>

<script>
import $util from "@/util/util.js"
import combinepay from '@/components/pay/combinepay.vue'

export default {
	components: {
		combinepay
	},
	data() {
		return {
			goodsId: '',
			goodsDetail: {},
			quantity: 1,
			fromShareUserId: '', // 分享者ID
			deliveryType: 1, // 配送方式：1-快递物流，0-门店自提
			address: null, // 收货地址
			address_id: 0, // 地址ID
			showpay: false, // 显示支付弹窗
			orderId: '', // 订单ID
			orderData: null // 订单数据（包含body等信息）
		}
	},
	
	computed: {
		// 计算总价
		totalPrice() {
			const price = parseFloat(this.goodsDetail.s_price || 0)
			return (price * this.quantity).toFixed(2)
		}
	},
	
	onLoad(options) {
		this.goodsId = options.id || options.shopid
		this.quantity = parseInt(options.num) || 1
		this.fromShareUserId = options.shareUserId || '' // 保存分享者ID
		
		this.getGoodsDetail()
		this.getDefaultAddress()
		
		// 监听地址选择
		$util.ListenerEvent('select_addess', (data) => {
			if (data && data.id) {
				this.address = data
				this.address_id = data.id
			}
		})
	},
	
	methods: {
		// 获取商品详情
		getGoodsDetail() {
			$util.showProgress()
			$util.ajax({
				url: 'mall/get_detail',
				id: this.goodsId
			}, (res) => {
				$util.hideProgress()
				if (res.code == 1) {
					this.goodsDetail = res.data
					// 处理图片
					if (res.data.images) {
						if (typeof res.data.images === 'string' && res.data.images.trim()) {
							const imageArray = res.data.images.split(',').filter(img => img && img.trim())
							this.goodsDetail.image = imageArray[0] || res.data.image
						} else if (Array.isArray(res.data.images) && res.data.images.length > 0) {
							this.goodsDetail.image = res.data.images[0]
						}
					}
				} else {
					$util.toast(res.msg || '获取商品详情失败')
				}
			})
		},
		
		// 获取默认地址
		getDefaultAddress() {
			$util.ajax({
				url: 'share/get_default'
			}, (res) => {
				if (res.code == 1 && res.data) {
					this.address = res.data
					this.address_id = res.data.id
				}
			})
		},
		
		// 选择地址
		selectAddress() {
			// 统一跳转到地址列表页
			$util.openwin('/pages/shop/addresslist/addresslist')
		},
		
		// 减少数量
		decreaseQuantity() {
			if (this.quantity > 1) {
				this.quantity--
			}
		},
		
		// 增加数量
		increaseQuantity() {
			this.quantity++
		},
		
		// 选择配送方式
		selectDelivery(type) {
			this.deliveryType = type
			// 切换到快递时，如果没有地址则获取默认地址
			if (type === 1 && !this.address) {
				this.getDefaultAddress()
			}
		},
		
		// 确认购买
		confirmBuy() {
			// 检查登录
			if (!$util.isLogin()) {
				$util.login()
				return
			}
			
			// 如果是快递物流，检查是否有地址
			if (this.deliveryType === 1 && !this.address) {
				$util.toast('请选择收货地址')
				this.selectAddress()
				return
			}
			
			// 创建订单
			this.createOrder()
		},
		
		// 创建订单
		createOrder() {
			$util.showProgress()
			
			let params = {
				url: 'share/create_order',
				id: this.goodsId,
				num: this.quantity,
				delivery_type: this.deliveryType,
				type: 1 // 立即购买
			}
			
			// 快递物流时传递地址ID
			if (this.deliveryType === 1 && this.address_id) {
				params.address_id = this.address_id
			}
			
			// 如果有分享者ID，也一并传递
			if (this.fromShareUserId) {
				params.shareUserId = this.fromShareUserId
			}
			
			$util.ajax(params, (res) => {
				$util.hideProgress()
				if (res.code == 1) {
					// 订单创建成功，保存订单ID和完整数据
					this.orderId = res.data.order_id || res.data.id
					this.orderData = res.data // 保存完整的订单数据
					this.showpay = true
				} else {
					$util.toast(res.msg || '订单创建失败')
				}
			})
		},
		
		// 支付
		gopay(payInfo) {
			this.showpay = false
			$util.showProgress()
			
			// 构建支付数据
			let paydata = {
				url: 'Pay/creat_order',
				out_trade_no: this.orderData && this.orderData.out_trade_no ? this.orderData.out_trade_no : this.orderId, // 使用share/create_order返回的out_trade_no
				trueprice: this.totalPrice,
				title: this.goodsDetail.title || '商品购买',
				// 使用创建订单接口返回的body，如果没有则使用默认值
				body: this.orderData && this.orderData.body ? this.orderData.body : 'shop_order',
				paytype: payInfo.payMethod || 2 // 支付方式
			}
			
			// 如果使用了谷粒或提货单
			if (payInfo.guliAmount > 0) {
				paydata.guliAmount = payInfo.guliAmount
			}
			if (payInfo.tihuodanAmount > 0) {
				paydata.tihuodanAmount = payInfo.tihuodanAmount
			}
			
			// 如果有支付密码，传递密码
			if (payInfo.password) {
				paydata.pass = payInfo.password
			}
			
			// 调用支付
			$util.topay(paydata, (status, data) => {
				if (status == 1) {
					// 支付成功
					$util.alert('支付成功！', () => {
						// 跳转到订单列表
						$util.openwin('/pages/memberinfo/order/order')
					})
				} else {
					// 支付失败
					// 优化错误提示，避免显示[object Object]
					let errorMsg = '支付失败';
					if (typeof data === 'string') {
						errorMsg = data;
					} else if (data && typeof data === 'object') {
						if (data.errMsg) {
							errorMsg = data.errMsg;
						} else if (data.msg) {
							errorMsg = data.msg;
						} else {
							errorMsg = JSON.stringify(data);
						}
					}
					$util.alert(errorMsg)
				}
			})
		},
		
		// 获取图片
		getimg(path) {
			if (!path) return ''
			// 如果是数组，取第一张
			if (Array.isArray(path)) {
				path = path[0] || ''
			}
			// 如果是逗号分隔的字符串，取第一张
			if (typeof path === 'string' && path.includes(',')) {
				path = path.split(',')[0]
			}
			return $util.get_img(path)
		}
	}
}
</script>

<style scoped>
.page {
	width: 100%;
	min-height: 100vh;
	background: #f5f5f5;
}

/* 商品信息卡片 */
.goods-card {
	margin: 20rpx;
	padding: 30rpx;
	background: #ffffff;
	border-radius: 20rpx;
	display: flex;
	flex-direction: row;
}

.goods-image-box {
	width: 180rpx;
	height: 180rpx;
	border-radius: 16rpx;
	overflow: hidden;
	margin-right: 24rpx;
	flex-shrink: 0;
}

.goods-image {
	width: 100%;
	height: 100%;
}

.goods-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.goods-title {
	font-size: 28rpx;
	color: #333333;
	line-height: 40rpx;
	font-weight: 500;
	/* 最多显示3行 */
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 3;
	overflow: hidden;
	text-overflow: ellipsis;
}

.price-box {
	display: flex;
	flex-direction: row;
	align-items: baseline;
	margin-top: 12rpx;
}

.price-symbol {
	font-size: 24rpx;
	color: #FF6B6B;
	font-weight: bold;
}

.price-value {
	font-size: 36rpx;
	color: #FF6B6B;
	font-weight: bold;
	margin-left: 4rpx;
}

.price-unit {
	font-size: 22rpx;
	color: #FF6B6B;
	margin-left: 4rpx;
}

/* 收货地址卡片 */
.address-card {
	margin: 0 20rpx 20rpx;
	padding: 30rpx;
	background: #ffffff;
	border-radius: 20rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
}

.address-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background: rgba(102, 126, 234, 0.1);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.address-content {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.address-header {
	display: flex;
	flex-direction: row;
	align-items: center;
	margin-bottom: 8rpx;
}

.address-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	margin-right: 20rpx;
}

.address-phone {
	font-size: 26rpx;
	color: #666666;
}

.address-detail {
	font-size: 26rpx;
	color: #666666;
	line-height: 38rpx;
}

.address-empty {
	font-size: 28rpx;
	color: #999999;
}

.address-arrow {
	margin-left: 20rpx;
}

/* 数量卡片 */
.quantity-card {
	margin: 0 20rpx 20rpx;
	padding: 30rpx;
	background: #ffffff;
	border-radius: 20rpx;
}

.card-row {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
}

.label {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
}

.quantity-control {
	display: flex;
	flex-direction: row;
	align-items: center;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	border: 2rpx solid #e0e0e0;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s;
}

.quantity-btn.disabled {
	background: #f5f5f5;
	border-color: #e0e0e0;
}

.quantity-input {
	width: 100rpx;
	height: 60rpx;
	border-top: 2rpx solid #e0e0e0;
	border-bottom: 2rpx solid #e0e0e0;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0 -2rpx;
}

.quantity-value {
	font-size: 30rpx;
	color: #333333;
	font-weight: 500;
}

/* 配送方式卡片 */
.delivery-card {
	margin: 0 20rpx 20rpx;
	padding: 30rpx;
	background: #ffffff;
	border-radius: 20rpx;
}

.card-title {
	margin-bottom: 24rpx;
}

.title-text {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
}

.delivery-options {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.delivery-option {
	padding: 24rpx;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
	transition: all 0.3s;
}

.delivery-option.active {
	border-color: #667eea;
	background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
}

.option-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background: #f5f5f5;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
	transition: all 0.3s;
}

.delivery-option.active .option-icon {
	background: rgba(102, 126, 234, 0.1);
}

.option-content {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.option-title {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	margin-bottom: 6rpx;
	transition: all 0.3s;
}

.option-title.active {
	color: #667eea;
}

.option-desc {
	font-size: 24rpx;
	color: #999999;
}

.option-check {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.check-circle {
	width: 20rpx;
	height: 20rpx;
	border: 2rpx solid #cccccc;
	border-radius: 50%;
}

/* 小计卡片 */
.total-card {
	margin: 0 20rpx 20rpx;
	padding: 30rpx;
	background: #ffffff;
	border-radius: 20rpx;
}

.total-price {
	display: flex;
	flex-direction: row;
	align-items: baseline;
}

.total-symbol {
	font-size: 24rpx;
	color: #FF6B6B;
	font-weight: bold;
}

.total-value {
	font-size: 40rpx;
	color: #FF6B6B;
	font-weight: bold;
	margin-left: 4rpx;
}

/* 底部操作栏 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #ffffff;
	padding: 20rpx;
	box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
	z-index: 100;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
}

.price-summary {
	display: flex;
	flex-direction: row;
	align-items: baseline;
	flex: 1;
}

.summary-label {
	font-size: 28rpx;
	color: #666666;
}

.summary-symbol {
	font-size: 24rpx;
	color: #FF6B6B;
	font-weight: bold;
	margin-left: 8rpx;
}

.summary-value {
	font-size: 40rpx;
	color: #FF6B6B;
	font-weight: bold;
}

.btn-confirm {
	width: 260rpx;
	height: 88rpx;
	background: linear-gradient(135deg, #667eea, #764ba2);
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
	margin-left: 20rpx;
}

.btn-text {
	font-size: 30rpx;
	color: #ffffff;
	font-weight: bold;
}
</style>
